﻿@page "/Login"
@layout LoginLayout
@using BlazorServerAuth.Components.Layout
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.Server
@using System.Security.Claims
@inject AuthenticationStateProvider AuthStateProvider
@inject NavigationManager NavigationManager
@inject Blazored.LocalStorage.ILocalStorageService localStorage

用户名：<InputText @bind-Value=@UserName></InputText>
<br />
密码：<InputText @bind-Value="@Password"></InputText>
<br />
<button @onclick="@SignIn" class="btn btn-primary">登录</button>

@code {

    string UserName = "超超TimChen44";
    string Password = "保密";

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            if (await localStorage.ContainKeyAsync("UserName"))
            {
                //读取登录状态，因为是Demo所以直接存储用户名，实际项目中应该是一个加密数据或者随机标识符
                UserName = await localStorage.GetItemAsync<string>("UserName");

                await InvokeAsync(StateHasChanged);

                //身份验证
                await BuildingIdentity(UserName);
            }
        }
    }

    private async void SignIn()
    {
        //验证账号密码
        //身份验证
        //构建身份
        await BuildingIdentity(UserName);
    }

    //构建身份
    public async Task BuildingIdentity(string userName)
    {
        var identity = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Name, userName),
                new Claim("UPMaster", "梦中百大UP主"),
            }, "Custom Authentication");
        var user = new ClaimsPrincipal(identity);

        AuthenticationState state = new AuthState(user)
            {
                IsLike = true,
                Coining = 2,
            };

        var authStateProvider = (ServerAuthenticationStateProvider)AuthStateProvider;

        var ss = await authStateProvider.GetAuthenticationStateAsync();
        authStateProvider.SetAuthenticationState(Task.FromResult(state));

        //用户名写入存储
        await localStorage.SetItemAsStringAsync("UserName", userName);

        var uri = new Uri(NavigationManager.Uri);
        var ReturnUrl = System.Web.HttpUtility.ParseQueryString(uri.Query)["ReturnUrl"];
        NavigationManager.NavigateTo(string.IsNullOrWhiteSpace(ReturnUrl) ? "/" : ReturnUrl);
    }
}